import { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import Taro from '@tarojs/taro'
import { Button } from '@tarojs/components'
import { AtModal, AtModalAction, AtModalContent, AtModalHeader } from 'taro-ui'

import { RootState } from 'src/store'
import { setUserInfo } from 'src/store/slice/user'
import * as api from 'src/api'
import { setToken } from 'src/utils/app'

import './index.scss'

export default ({ visible, onClose, getDate }) => {
  const [loading, setLoding] = useState(false)
  const pid = useSelector((state: RootState) => state.user.pid)
  const dispatch = useDispatch()

  const getUserInfo = async () => {
    setLoding(true)
    try {
      const { userInfo } = (await Taro.getUserProfile({
        desc: '用于完善会员资料',
      })) as any
      console.log(userInfo)
      if (pid) {
        userInfo.spread_spid = pid
      }
      const { code } = await Taro.login()
      const { token, user } = await api.login(code, userInfo)
      setLoding(false)
      dispatch(setUserInfo(user))
      setToken(token)
      getDate()
      onClose(user.phone)
    } catch (error) {
      setLoding(false)
      Taro.showToast({
        title: '登陆失败',
        icon: 'none',
      })
    }
  }

  return (
    <AtModal className="bind-phone-number" isOpened={visible}>
      <AtModalHeader>登陆</AtModalHeader>
      <AtModalContent>请授权用户信息，登陆小程序</AtModalContent>
      <AtModalAction>
        <Button onClick={onClose}>取消</Button>
        <Button onClick={getUserInfo} loading={loading} disabled={loading}>
          授权
        </Button>
      </AtModalAction>
    </AtModal>
  )
}
